#!/usr/bin/env python3

import socket
import os
import signal
import vt

def outRecvData(sd):
    data, addr = sd.recvfrom(1024)

    data = data.decode()

    if data == 'exit':
        return None

    vt.run([vt.save(), vt.goto(1, 1), vt.LINE, vt.color("客户端接受到(%s): %s" % (addr[0], data), vt.RED), vt.load()])
    #  print("\033[s\033[1;1H\033[2K客户端接受到(%s): %s\033[u"
                #  % (addr[0], data), end='', flush=True)

    return addr

def myExit(sig, stack):
    os._exit(0)

def main():
    signal.signal(signal.SIGTERM, myExit)

    sd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sd.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    addr = ('255.255.255.255', 9000)

    vt.clear(False)
    #  print("\033[2J", end="", flush=True)

    if os.fork() == 0:
        while outRecvData(sd):
            pass
    else:
        while True:
            data = input(vt.goto(5, 1) + vt.run(vt.LINE) + vt.color("客户端发送:", vt.BLUE))
            #  data = input("\033[5;1H\033[2K客户端发送: ")
            sd.sendto(data.encode(), addr)
            if data == 'exit':
                break

    sd.close()
    os.kill(0, signal.SIGTERM)


if __name__ == "__main__":
    main()
